﻿/// <reference path="General.js" />
/// <reference path="Browser.js" />

var Ajax = {};
Ajax._rgxUrlHasParams = new RegExp("\\?|#");

Ajax.Get = function Get(url, params, callback, callbackParams)
{
	var request = Ajax.CreateRequest();
	Ajax.AttachCallback(request, callback, callbackParams);

	if (typeof (params) != "string")
		params = Ajax.ConvertParamsToUrl(params);
	url = Ajax.AppendToUrl(url, params);

	if (Browser.get_Name() == "MSIE")
		url = Ajax.AppendToUrl(url, Ajax.GetDummyParam());

	request.open("GET", url, true);
	request.send("");
}
Ajax.Post = function Post(url, params, callback, callbackParams)
{
	var request = Ajax.CreateRequest();
	Ajax.AttachCallback(request, callback, callbackParams);

	if (typeof (params) != "string")
		params = Ajax.ConvertParamsToUrl(params);

	if (Browser.get_Name() == "MSIE")
		url = Ajax.AppendToUrl(url, Ajax.GetDummyParam());

	request.open("POST", url, true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", params.length);
	//	request.setRequestHeader("Connection", "close");

	request.send(params);
}
Ajax.CreateRequest = function CreateRequest()
{
	if (window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}
	else
	{
		try
		{
			return new ActiveXObject("MSXML2.XMLHTTP");
		}
		catch (olderIE)
		{
			try
			{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				throw "Browser does not support AJAX.";
			}
		}
	}
}
Ajax.AttachCallback = function AttachCallback(request, callback, callbackParams)
{
	request.onreadystatechange = function onreadystatechange()
	{
		if (request.readyState == 4)
		{
			if (typeof (callback) == "function")
				callback(request.responseText, request, callbackParams);
		}
	}
}
Ajax.ConvertParamsToUrl = function ConvertParamsToUrl(params)
{
	var sb = new StringBuilder();
	var first = true;
	for (var i in params)
	{
		if (!first)
			sb.Append("&");
		first = false;

		sb.Append(encodeURIComponent(i));
		sb.Append("=");
		sb.Append(encodeURIComponent(params[i]));
	}
	return sb.toString();
}
Ajax.AppendToUrl = function AppendToUrl(url, paramStr)
{
	return url + (Ajax._rgxUrlHasParams.test(url) ? "&" : "?") + paramStr;
}
Ajax.AppendToHash = function AppendToHash(hash, paramStr)
{
	return hash + (hash == null || hash == "" ? "#" : (hash.length > 1 ? "&" : "")) + paramStr;
}
Ajax.GetDummyParam = function GetDummyParam()
{
	return "dummy=" + Math.floor(Math.random() * 1000000 + 1);
}

